﻿using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
using MediaBrowser.CustomControls.CustomEvent;

namespace MediaBrowser.CustomControls.Panels
{
    /// <summary>
    /// Logique d'interaction pour FlipPanel.xaml
    /// </summary>
    public partial class FlipPanel : UserControl
    {
        public FlipPanel()
        {
            InitializeComponent();
        }

        public void CustomizeDataTemplate(DataTemplate dt)
        {
            if (flipPanel.ItemTemplate != dt)
            {
                #region Détache les deux ancien contenus
                if (flipPanel.ItemTemplate != null)
                {
                    DependencyObject dl = flipPanel.ItemContainerGenerator.ContainerFromIndex(0);
                    //Content Front
                    ContentPresenter myContentPresenterl = FindVisualChild<ContentPresenter>(dl, "contentFront");
                    if (myContentPresenterl != null)
                    {
                        DataTemplate myTemplatel = (DataTemplate)this.Resources["frontTemplate"];
                        Grid gl = (Grid)myTemplatel.FindName("GridFrontTemplate", myContentPresenterl);
                        gl.Children.Clear();
                    }

                    //Content Back
                    ContentPresenter myContentPresenterlB = FindVisualChild<ContentPresenter>(dl, "contentBack");
                    if (myContentPresenterlB != null)
                    {
                        DataTemplate myTemplatelB = (DataTemplate)this.Resources["backTemplate"];
                        Grid glB = (Grid)myTemplatelB.FindName("GridBackTemplate", myContentPresenterlB);
                        glB.Children.Clear();
                    }

                }

                #endregion

                flipPanel.ItemTemplate = dt;
                flipPanel.UpdateLayout();
                DependencyObject d = flipPanel.ItemContainerGenerator.ContainerFromIndex(0);
                //Content Front
                ContentPresenter myContentPresenter = FindVisualChild<ContentPresenter>(d, "contentFront");
                if (myContentPresenter != null)
                {
                    DataTemplate myTemplate = (DataTemplate)this.Resources["frontTemplate"];
                    Grid g = (Grid)myTemplate.FindName("GridFrontTemplate", myContentPresenter);
                    if (g.Children.Count == 0) { g.Children.Add(FrontTemplate); }
                }

                //Content Back
                ContentPresenter myContentPresenterB = FindVisualChild<ContentPresenter>(d, "contentBack");
                if (myContentPresenterB != null)
                {
                    DataTemplate myTemplateB = (DataTemplate)this.Resources["backTemplate"];
                    Grid gB = (Grid)myTemplateB.FindName("GridBackTemplate", myContentPresenterB);
                    if (gB.Children.Count == 0) { gB.Children.Add(BackTemplate); }
                }
            }
        }

        private childItem FindVisualChild<childItem>(DependencyObject obj, String Name) where childItem : DependencyObject
        {

            for (int i = 0; i < VisualTreeHelper.GetChildrenCount(obj); i++)
            {

                DependencyObject child = VisualTreeHelper.GetChild(obj, i);

                if (child != null && child is childItem && child.GetValue(FrameworkElement.NameProperty).Equals(Name))
                    return (childItem)child;
                else
                {
                    childItem childOfChild = FindVisualChild<childItem>(child, Name);
                    if (childOfChild != null)
                        return childOfChild;
                }
            }

            return null;
        }

        public void Template_OnControlClosed(object sender)
        {
            if (sender.Equals(FrontTemplate))
            {
                CustomizeDataTemplate(Resources["flipItemFromTemplateWithout3D"] as DataTemplate);
            }
            else
            {
                CustomizeDataTemplate(Resources["flipItemBackTemplateWithout3D"] as DataTemplate);
            }
            CloseEventArgs args = new CloseEventArgs(CloseEvent, this);
            RaiseEvent(args);
        }

        #region DPS

        public ClosableControl FrontTemplate
        {
            get { return (ClosableControl)GetValue(FrontTemplateProperty); }
            set { SetValue(FrontTemplateProperty, value); }
        }

        public static DependencyProperty FrontTemplateProperty =
        DependencyProperty.Register("FrontTemplate", typeof(ClosableControl), typeof(FlipPanel),
        new PropertyMetadata(FrontTemplateChanged));

        private static void FrontTemplateChanged(DependencyObject sender, DependencyPropertyChangedEventArgs e)
        {
            FlipPanel f = sender as FlipPanel;
            if (f == null)
                return;
            f.FrontTemplate.OnControlClosed += f.Template_OnControlClosed;
        }
        
        public ClosableControl BackTemplate
        {
            get { return (ClosableControl)GetValue(BackTemplateProperty); }
            set { SetValue(BackTemplateProperty, value); }
        }

        public static DependencyProperty BackTemplateProperty =
        DependencyProperty.Register("BackTemplate", typeof(ClosableControl), typeof(FlipPanel),
        new PropertyMetadata(BackTemplateChanged));

        private static void BackTemplateChanged(DependencyObject sender, DependencyPropertyChangedEventArgs e)
        {
            FlipPanel f = sender as FlipPanel;
            if (f == null)
                return;
            f.BackTemplate.OnControlClosed += f.Template_OnControlClosed;
        }

        public bool IsUILoaded
        {
            get { return (bool)GetValue(IsUILoadedProperty); }
            set { SetValue(IsUILoadedProperty, value); }
        }

        public static DependencyProperty IsUILoadedProperty =
        DependencyProperty.Register("IsUILoaded", typeof(bool), typeof(FlipPanel),
        new PropertyMetadata(IsUILoadedChanged));

        private static void IsUILoadedChanged(DependencyObject sender, DependencyPropertyChangedEventArgs e)
        {
            FlipPanel f = sender as FlipPanel;
            if (f == null)
                return;

            if (f.IsUILoaded)
            {
                f.CustomizeDataTemplate(f.Resources["flipItemTemplate"] as DataTemplate);
            }
        }

        #endregion

        #region Event

        public static readonly RoutedEvent CloseEvent =
          EventManager.RegisterRoutedEvent(
          "OnClose", RoutingStrategy.Bubble,
          typeof(CloseEventHandler),
          typeof(FlipPanel));

        //add remove handlers
        public event CloseEventHandler OnClose
        {
            add { AddHandler(CloseEvent, value); }
            remove { RemoveHandler(CloseEvent, value); }
        }

        #endregion
                
    }
}
